package cn.study.vue_project_xxx.manager;

import cn.study.vue_project_xxx.entity.po.UserLogin;
import cn.study.vue_project_xxx.mapper.TAdminMapper;
import cn.study.vue_project_xxx.mapper.UserInfoMapper;
import cn.study.vue_project_xxx.mapper.UserLoginMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

import static cn.study.vue_project_xxx.common.enumeration.MapKey.adminKey;
import static cn.study.vue_project_xxx.common.enumeration.MapKey.userLoginKey;

@Component
public class UserLoginManager {


    @Resource
    UserLoginMapper userLoginMapper;

    @Resource
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    TAdminMapper adminMapper;




    public Integer saveUserLogin(UserLogin userLogin) {
        // 密码md5 加密
        userLogin.setLoginPassword(bCryptPasswordEncoder.encode(userLogin.getLoginPassword()));
        return userLoginMapper.insert(userLogin);
    }

    public UserLogin getUserLoginDetail(UserLogin userLogin) {
        // 根据用户登录表单查询数据
        String encode = bCryptPasswordEncoder.encode(userLogin.getLoginPassword());
        List<UserLogin> userLogins = userLoginMapper.selectList(new LambdaUpdateWrapper<UserLogin>()
                .eq(UserLogin::getLoginNumber, userLogin.getLoginNumber())
                .eq(UserLogin::getLoginPassword, encode)
        );
        return userLogins.stream().filter(item -> item.getLoginNumber()
                        .equals(userLogin.getLoginNumber())).findFirst().orElse(null);
    }

    public HashMap<String, Integer> deleteAdmin(List<Long> userIds) {
        //执行删除     删除用户表和关联登录表
        int i = adminMapper.deleteBatchIds(userIds);
        LambdaQueryWrapper<UserLogin> userLoginLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLoginLambdaQueryWrapper.in(UserLogin::getLoginUserId,userIds);
        int deleteUserLogin = userLoginMapper.delete(userLoginLambdaQueryWrapper);
        HashMap<String, Integer> map = new HashMap<>();
        map.put(adminKey,i);
        map.put(userLoginKey,deleteUserLogin);
        return map;
    }
}
